package org.itboys.advertisement.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.itboys.advertisement.cache.AdvertisementLoader;
import org.itboys.advertisement.dto.AdvertisementItemVO;
import org.itboys.advertisement.dto.AdvertisementVO;
import org.itboys.advertisement.dto.LinkTagArray;
import org.itboys.advertisement.entity.Advertisement;
import org.itboys.advertisement.entity.AdvertisementItem;
import org.itboys.advertisement.entity.Adzone;
import org.itboys.advertisement.entity.LinkTag;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

/**
 * 广告管理
 */
@Service
public class AdvertisementService extends BaseService<Advertisement, Long> {

	private static final long serialVersionUID = 1L;

	@Resource(name="advertisementDs")
    private MongoDataSource advertisementDs;

    @Autowired
    private AdzoneService adzoneService;
    
    @Autowired
    private AdvertisementItemService advertisementItemService;

    @Resource(name="advertisementLoader")
    private AdvertisementLoader advertisementLoader;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return advertisementDs;
    }

    @Override
    protected Class<Advertisement> getEntityClass() {
        return Advertisement.class;
    }

    /**
     * 根据广告位的key 获取广告相关信息
     * @param adzoneKey
     * @return
     */
    public AdvertisementVO getCurrentAdvertisement(String adzoneKey) {
        return advertisementLoader.get(adzoneKey);
    }

    public Map<String , AdvertisementVO> getCurrentAdvertisementMap(List<String> adzoneKeys) {
        return advertisementLoader.getValueMap(adzoneKeys);
    }


    /**
     * 根据广告位的key 加载相关数据
     * @param adzoneKey
     * @return
     */
    public AdvertisementVO getAdvertisementVO(String adzoneKey) {
        if (StringUtils.isBlank(adzoneKey)) {
            return null;
        }
        Adzone adzone = adzoneService.getByField("key", adzoneKey);
        if (adzone == null) {
            return null;
        }
        Advertisement advertisement = getCurrentAdvertisement(adzone.getId());
        if (advertisement == null) {
            return null;
        }
        List<AdvertisementItem> items = advertisementItemService.getItems(advertisement.getId());
        List<AdvertisementItemVO> itemVOs = Lists.transform(items, input -> {
            AdvertisementItemVO itemVO = new AdvertisementItemVO();
            itemVO.setClickUrl(input.getClickUrl());
            itemVO.setFilePath(input.getFilePath());
            itemVO.setTitle(input.getTitle());
            return itemVO;
        });

        AdvertisementVO advertisementVO = new AdvertisementVO();
        advertisementVO.setName(adzone.getName());
        advertisementVO.setLinkTags(advertisement.getLinkTags());
        advertisementVO.setItems(itemVOs);

        return advertisementVO;
    }

    /**
     * 获得当前的 广告
     * @return
     */
    public Advertisement getCurrentAdvertisement(long adzoneId) {
        //TODO 现在先写死 以后有包时的广告可不是这样的
        List<Advertisement> advertisementList = super.findByField("adzoneId", adzoneId);
        return CollectionUtils.isEmpty(advertisementList) ? null : advertisementList.get(0);
    }
    
    /**
     * 新增或者修改
     * @param advertisement
     * @return
     */
    public boolean insert(Advertisement advertisement){
    	try{
    		if(advertisement.getId() != 0){
    			super.update(advertisement);
    		}else{
    			super.save(advertisement);
    		}
    		return true;
    	}catch(Exception e){
    		logger.error("AdvertisementService.insert error, Advertisement=" + ToStringBuilder.reflectionToString(advertisement), e);
    		return false;
    	}
    }
    
    /**
     * 删除
     * @param advertisementId
     * @return
     */
    public boolean dele(Long advertisementId){
    	try{
    		super.delete(advertisementId);
    		return true;
    	}catch(Exception e){
    		logger.error("AdvertisementService.dele error, advertisementId=" + advertisementId, e);
    		return false;
    	}
    }
    
    /**
     * 查询并分页
     * @param request
     * @return
     */
    public Page<Advertisement> listAndPage(HttpServletRequest request){
    	Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		Page<Advertisement> page = super.pageQuery(param, request);
		for(Advertisement adv : page.getData()){//用desc暂时替代导链标签  如果导链标签为空  则设置desc为NULL
			StringBuffer sb = new StringBuffer();
			if(adv.getLinkTags() != null){
				for(LinkTag lt : adv.getLinkTags()){
					sb.append(lt.getTag() + ",");
				}
				adv.setDesc(sb.toString());
			}else{
				adv.setDesc(null);
			}
		}
		
		return page;
    }
    
    /**
     * 对广告信息设置导链标签
     * @param linkTag
     * @return
     */
    public boolean setLinkTag(LinkTagArray linkTagArray, Long advertisementId){
    	try{
    		List<LinkTag> lkt = Lists.newArrayListWithExpectedSize(linkTagArray.getTags().length);
    		if(linkTagArray != null && linkTagArray.getTags().length > 0){
    			for(int i = 0; i < linkTagArray.getTags().length; i++){
    				LinkTag lt = new LinkTag();
    				lt.setLinkUrl(linkTagArray.getLinkUrls()[i]);
    				lt.setTag(linkTagArray.getTags()[i]);
    				lt.setType(linkTagArray.getTypes()[i]);
    				lkt.add(lt);
    			}
    		}
    		super.update(advertisementId, "linkTags", lkt);
    		
    		/*Advertisement advertisement = super.getById(advertisementId);
    		advertisement.setLinkTags(lkt);
    		super.update(advertisement);*/
    		
    		return true;
    	}catch(Exception e){
    		logger.error("AdvertisementService.setLinkTag error", e);
    		return false;
    	}
    }
}
